package com.nineyang.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/*
 自定义消息转换器
 1.引入能够处理需要格式的库 jackson-dataformat-yaml
 2.在配置文件中进行配置，新增一种媒体类型
 3.编写自定义消息转换类，继承AbstractHttpMessageConverter并实现其中的方法。
 4.在配置类中配置消息转换器。
 */
public class YamlHttpMessageConverter extends AbstractHttpMessageConverter {

    private final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));


    public YamlHttpMessageConverter() {
        // 将消息转换器和媒体类型绑定到一起
        super(new MediaType("text", "yaml", StandardCharsets.UTF_8));
    }

    @Override
    protected boolean supports(Class clazz) {
        // 表示User类型的数据支持yaml，其他类型不支持。
        return Object.class.isAssignableFrom(clazz );
    }

    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        this.objectMapper.writeValue(outputMessage.getBody(), o);
    }
}
